package com.yuandengta.nio;

import io.netty.buffer.ByteBuf;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Author:Hardy
 * @QQ:2937270766
 * @官网：http://www.yuandengta.com
 */
public class GroupChatServer {
    //定义属性
    private ServerSocketChannel linstenChannel;
    private Selector selector;
    private static final int PORT = 6667;

    //初始化工作
    public GroupChatServer(){
        try{
            //获得选择器
            selector = Selector.open();
            linstenChannel = ServerSocketChannel.open();
            //绑定端口
            linstenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            linstenChannel.configureBlocking(false);
            //将listenChannel 注册到selector上
            linstenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    //监听
    public void listen(){
        try {
            //循环处理
            while(true){
                int count = selector.select();
                if(count > 0){//有事件要处理
                    //遍历得到selectionKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while(iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        //监听到accept
                        if(key.isAcceptable()){
                            SocketChannel sc = linstenChannel.accept();
                            sc.configureBlocking(false);
                            //将该sc注册到selector
                            sc.register(selector,SelectionKey.OP_READ);
                            // 给出上线提示
                            System.out.println(sc.getRemoteAddress()+" 上线 ");
                        }
                        if(key.isReadable()){//通道发生read事件，通道是可读状态
                            //处理读
                            readData(key);
                        }
                        //当前的key删除，防止重复处理
                        iterator.remove();
                    }
                }else{
                    System.out.println("等待......");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {

        }
    }

    //读取客户端消息
    private void readData(SelectionKey key){
        //定义一个SocketChannel
        SocketChannel channel = null;
        try {
            //取到关联的channel
            channel = (SocketChannel)key.channel();
            //创建Buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            int count = channel.read(buffer);
            //根据count的值做处理
            if(count > 0){
                //把缓冲区的数据转换成字符串
                String msg = new String(buffer.array());
                //输出该消息
                System.out.println("from client : " + msg);
                //向其它客户端转发消息
                sendInfoToOtherClients(msg,channel);
            }
        }catch(IOException e){
            try {
                System.out.println(channel.getRemoteAddress() + "离线了");
                //取消注册
                key.cancel();
                channel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    //转发消息给其它客户端（通道),去掉自己
    private void sendInfoToOtherClients(String msg,SocketChannel self) throws IOException {
        System.out.println("服务器转发消息中.....");
        //遍历所有注册到selector上的SocketChannel并排除自己
         for(SelectionKey key:selector.keys()){
             //通过key取出对应的channel
             Channel targetChannel = key.channel();
             //排除自己
             if(targetChannel instanceof SocketChannel && targetChannel != self){
                 SocketChannel dest = (SocketChannel)targetChannel;
                 //将msg存储到buffer
                 ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                 //将buffer数据写入通道
                 dest.write(buffer);
             }
         }
    }
    public static void main(String[] args) {
        new GroupChatServer().listen();
    }
}
